package com.cheetah.start.system.role.controller;

import cn.hutool.core.collection.CollUtil;
import com.cheetah.start.common.annotation.ApiCount;
import com.cheetah.start.common.annotation.Log;
import com.cheetah.start.common.base.result.Result;
import com.cheetah.start.common.base.result.ResultController;
import com.cheetah.start.common.base.result.ResultTree;
import com.cheetah.start.common.enums.BusinessTypeEnum;
import com.cheetah.start.common.enums.LogTypeEnum;
import com.cheetah.start.system.menu.domain.SysMenu;
import com.cheetah.start.system.role.service.SysRoleMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色权限控制器
 *
 * @author Feel
 * @date 2021/10/15
 */
@Api(tags = "角色权限管理")
@Slf4j
@ApiCount
@Validated
@CrossOrigin
@RestController
@RequestMapping("/roleMenu")
public class SysRoleMenuController extends ResultController {

    @Autowired
    private SysRoleMenuService sysRoleMenuService;


    /**
     * 获取角色权限
     *
     * @param roleId 角色id
     * @return {@link Result}
     */
    @ApiOperation("获取角色权限")
    @GetMapping("/get")
    public ResultTree get(Integer roleId) {
        List<SysMenu> menuByRoleId = sysRoleMenuService.getMenuByRoleId(roleId);
        return dataTree(menuByRoleId);
    }

    /**
     * 前端需要使用的树
     *
     * @param roleId 角色id
     * @return {@link ResultTree}
     */
    @GetMapping("/getKey")
    public Result getKey(Integer roleId) {
        List<SysMenu> menuByRoleId = sysRoleMenuService.getMenuByRoleIdBase(roleId);
        List<Integer> select = new ArrayList<>();
        if (CollUtil.isNotEmpty(menuByRoleId)) {
            select = menuByRoleId.stream().map(SysMenu::getMenuId).collect(Collectors.toList());
        }
        List<String> res = new ArrayList<>();
        if (CollUtil.isNotEmpty(select)) {
            for (Integer integer : select) {
                res.add(integer.toString());
            }
        }
        return success(res);
    }

    /**
     * 添加
     *
     * @param roleId  角色id
     * @param menuIds 菜单id
     * @return {@link Result}
     */
    @ApiOperation("添加权限")
    @Log(title = "角色权限", describe = "添加", type = BusinessTypeEnum.ADD, logType = LogTypeEnum.OPERATE)
    @PostMapping("/add")
    public Result add(Integer roleId, String[] menuIds) {
        boolean res = sysRoleMenuService.add(roleId, menuIds);
        return decide(res);
    }
}
